package prj.carmap.mobile.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.model.HotKey;
import prj.carmap.mobile.process.SellerSearchProcess;
import prj.carmap.mobile.process.SellerTypeProcess;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.miaowang.salad.activity.MineInfoActivity;

/**
 * 商家搜索界面
 *
 */
public class SellerSearchActivity extends SherlockActivity {
	//private List<HotKey> hotkeys;
	static AsyncHttpClient client = new AsyncHttpClient();
	public String searchCond;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (CarmapApplication.popView != null)
		{
			CarmapApplication.popView.hide();
		}

		CarmapApplication.currentPage = "search";
		CarmapApplication.addActivity(this);
		//Application app = (Application) this.getApplication();

		/**
		 * 由于MapView在setContentView()中初始化,所以它需要在BMapManager初始化之后
		 */
		setContentView(R.layout.activity_seller_search);
		//View thisView = LayoutInflater.from(this).inflate(R.layout.activity_seller_search, null);
		// Inflate the custom view
//		View customNav = LayoutInflater.from(this).inflate(R.layout.nav_search_view, null);
//		// Attach to the action bar
//		// getSupportActionBar().setCustomView(customNav);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().hide();
//		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
//		getSupportActionBar().setCustomView(customNav);
//		customNav.setLayoutParams(lp);
		// ActionBarf返回按钮
		Button returnBtn = (Button) this.findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						SellerSearchActivity.this.finish();
					}
				});
		
		Button searchBtn = (Button) this.findViewById(R.id.seller_search_button);
		searchBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						EditText editText = (EditText) SellerSearchActivity.this.findViewById(R.id.search_condition);
						String key = editText.getText().toString();
						if ("".equals(key))
							key = "all";
						SellerSearchActivity.this.searchCond = key;
						CarmapApplication.popView = new DialogView(SellerSearchActivity.this);
						CarmapApplication.popView.show();
						client.get(
								CarmapApplication.SERVER_URL + "/rest/seller/search/" + key + "/"
										+ CarmapApplication.getInstance().getLocData().longitude
										+ "/"
										+ CarmapApplication.getInstance().getLocData().latitude + "/0",
								new SellerSearchProcess(SellerSearchActivity.this));
						if (!"all".equals(key)) {
							// 打开或创建test.db数据库
							SQLiteDatabase db = openOrCreateDatabase("carmap.db", Context.MODE_PRIVATE, null);
							// 创建person表
							db.execSQL("insert into history values('" + key + "', 'now')");
							db.close();
						}
					}
				});

		initMenuItem();
		ListView listView = (ListView) findViewById(R.id.search_history_view);
		List<Map<String, Object>> conds = new ArrayList<Map<String, Object>>();
		if (!tabbleIsExist("history")) {
			// 打开或创建test.db数据库
			SQLiteDatabase db = openOrCreateDatabase("carmap.db", Context.MODE_PRIVATE, null);
			// 创建person表
			db.execSQL("CREATE TABLE history (serach_cond VARCHAR, search_time VARCHAR)");
			db.close();
		}
		// 打开或创建test.db数据库
		SQLiteDatabase db = openOrCreateDatabase("carmap.db", Context.MODE_PRIVATE, null);
		Cursor c = db.rawQuery("SELECT * FROM history order by search_time desc", null);

		while (c.moveToNext())
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("searchCond", c.getString(c.getColumnIndex("serach_cond")));
			conds.add(map);
			if (conds.size() == 20)
				break;
		}
		c.close();
		db.close();

		// 生成适配器的Item和动态数组对应的元素
		// 生成适配器的Item和动态数组对应的元素
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, conds,// 数据源
				R.layout.list_history_view,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "searchCond" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.search_history_item });

		listView.setAdapter(listItemAdapter);
		// 添加点击
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ListView listView = (ListView) parent;
				Map<String, Object> map = (Map<String, Object>) listView.getItemAtPosition(position);
				SellerSearchActivity.this.searchCond = map.get("searchCond").toString();
				CarmapApplication.popView = new DialogView(SellerSearchActivity.this);
				CarmapApplication.popView.show();
				client.get(
						CarmapApplication.SERVER_URL
								+ "/rest/seller/search/"
								+ SellerSearchActivity.this.searchCond
								+ "/"
								+ CarmapApplication.getInstance().getLocData().longitude
								+ "/"
								+ CarmapApplication.getInstance().getLocData().latitude + "/0",
						new SellerSearchProcess(SellerSearchActivity.this));
			}
		});

		GridView gridView = (GridView) SellerSearchActivity.this.findViewById(R.id.search_hot_key);
		HotkeyAdapter hotkeyAdapter = new HotkeyAdapter(
				new JSONArray(), SellerSearchActivity.this, gridView, 4, 12);
		gridView.setAdapter(hotkeyAdapter);

		client.get(CarmapApplication.SERVER_URL + "/rest/hotkey",
				new AsyncHttpResponseHandler() {
					public void onSuccess(String content) {
						JSONArray jsonAry;
						try {
							jsonAry = new JSONArray(content);
						}
						catch (JSONException e) {
							return;
						}
						GridView gridView = (GridView) SellerSearchActivity.this.findViewById(R.id.search_hot_key);
						HotkeyAdapter hotkeyAdapter = new HotkeyAdapter(
								jsonAry, SellerSearchActivity.this, gridView, 4, 12);
						gridView.setAdapter(hotkeyAdapter);

					}
				});

		// listView.setOnItemClickListener(this);
	}

	@SuppressWarnings("deprecation")
	private void initMenuItem() {
		if ("type".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_type);
			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this.findViewById(R.id.item_type_image);
			itemImage.setImageResource(R.drawable.type_select);
			// 底部菜单文字
			TextView itemText = (TextView) this.findViewById(R.id.item_type_text);
			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		}
//		else if ("search".equals(CarmapApplication.currentPage)) {
//			// 底部菜单项
//			View menuItem = this.findViewById(R.id.menu_item_search);
//			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
//			// 底部菜单图标
//			ImageView itemImage = (ImageView) this.findViewById(R.id.item_search_image);
//			itemImage.setImageResource(R.drawable.search_select);
//			// 底部菜单文字
//			TextView itemText = (TextView) this.findViewById(R.id.item_search_text);
//			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
//		}
		else if ("mine".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_mine);
			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this.findViewById(R.id.item_mine_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this.findViewById(R.id.item_mine_text);
			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		}
		else if ("salad".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_salad);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_salad_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_salad_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
//		else if ("more".equals(CarmapApplication.currentPage)) {
//			// 底部菜单项
//			View menuItem = this.findViewById(R.id.menu_item_more);
//			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
//			// 底部菜单图标
//			ImageView itemImage = (ImageView) this.findViewById(R.id.item_more_image);
//			itemImage.setImageResource(R.drawable.more_select);
//			// 底部菜单文字
//			TextView itemText = (TextView) this.findViewById(R.id.item_more_text);
//			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
//		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SellerSearchActivity.this.startActivity(new Intent(SellerSearchActivity.this, MainActivity.class));
				SellerSearchActivity.this.finish();
			}
		});
		
		 view = (View) this.findViewById(R.id.menu_item_type);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SellerTypeProcess process = new SellerTypeProcess();
				process.setContext(SellerSearchActivity.this);
				process.getSellerTypes();
			}
		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				UserInfo userInfo = CarmapApplication.getInstance().userInfo;
//				if (userInfo == null) {
//					SellerSearchActivity.this.startActivity(new Intent(SellerSearchActivity.this, LoginActivity.class));
//				}
//				else {
//					SellerSearchActivity.this.startActivity(new Intent(SellerSearchActivity.this, ProfileActivity.class));
//				}
				SellerSearchActivity.this.startActivity(new Intent(SellerSearchActivity.this, MineInfoActivity.class));
			}
		});

//		view = (View) this.findViewById(R.id.menu_item_more);
//		view.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				SellerSearchActivity.this.startActivity(new Intent(SellerSearchActivity.this, MoreActivity.class));
//			}
//		});

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		super.onResume();
		CarmapApplication.currentPage = "search";
	}

	/**
	 * 判断某张表是否存在
	 *
	 * @param tabName
	 *            表名
	 * @return
	 */
	public boolean tabbleIsExist(String tableName) {
		boolean result = false;
		if (tableName == null) {
			return false;
		}

		SQLiteDatabase db = openOrCreateDatabase("carmap.db", Context.MODE_PRIVATE, null);
		Cursor cursor = null;
		try
		{
			String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='" + tableName.trim() + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}
		}
		catch (Exception e) {
		}
		finally {
			cursor.close();
			db.close();
		}
		return result;
	}

}

// 自定义适配器
class HotkeyAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private JSONArray hotkeys;
	private SellerSearchActivity context;
	private GridView gridView;
	private int cols;
	private int total = 0;
	private int topCount = 10;

	public HotkeyAdapter(JSONArray jsonAry, SellerSearchActivity context, GridView gridView, int COLS, int total) {
		super();
		this.hotkeys = jsonAry;
		try {
			for (int i = 0; i < hotkeys.length(); i++) {
				JSONObject json = hotkeys.getJSONObject(i);
				int count = json.getInt("count");
				if (count > topCount) {
					topCount = count;
				}

			}
		}
		catch (Exception ex) {
		}
		this.context = context;
		this.gridView = gridView;
		this.cols = COLS;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return 12;
	}

	@Override
	public Object getItem(int position) {
		try {
			if (position < hotkeys.length()) {
				return hotkeys.getJSONObject(position);
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		JSONObject json;
		try {
			if (position >= hotkeys.length())
			{
				convertView = inflater.inflate(R.layout.hotkey, null);
			}
			else
			{
				json = hotkeys.getJSONObject(position);
				HotKey hotkey = new HotKey();
				hotkey.key = json.getString("key");
				hotkey.count = json.getInt("count");
				convertView = inflater.inflate(R.layout.hotkey, null);
				((Button) convertView).setText(hotkey.key);
				if (hotkey.count > topCount * 0.8) {
					//((Button) convertView).setTextColor(ColorUtil.colorStr2Int(CarmapApplication.config.hotterColor));
					((Button) convertView).setBackgroundResource(R.drawable.search_hot_key_press);
				}
				else if (hotkey.count > topCount * 0.5) {
					//((Button) convertView).setTextColor(ColorUtil.colorStr2Int(CarmapApplication.config.hotColor));
					((Button) convertView).setBackgroundResource(R.drawable.search_hot_key_press);

				}
				((Button) convertView)
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Button button = (Button) v;
								context.searchCond = button.getText().toString();
								CarmapApplication.popView = new DialogView(context);
								CarmapApplication.popView.show();
								SellerSearchActivity.client.get(CarmapApplication.SERVER_URL
										+ "/rest/seller/search/"
										+ context.searchCond
										+ "/"
										+ CarmapApplication.getInstance().getLocData().longitude
										+ "/"
										+ CarmapApplication.getInstance().getLocData().latitude
										+ "/0",
										new SellerSearchProcess(context));
								// 打开或创建test.db数据库
								SQLiteDatabase db = context.openOrCreateDatabase("carmap.db", Context.MODE_PRIVATE, null);
								// 创建history表
								db.execSQL("insert into history values('" + context.searchCond + "', 'now')");
								db.close();
							}
						});

			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}

		//WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		ViewGroup.LayoutParams lp = gridView.getLayoutParams();
		AbsListView.LayoutParams params = new AbsListView.LayoutParams((lp.width - 6) / 4, (lp.height - 2) / 3);
		convertView.setLayoutParams(params);
		return convertView;
	}
}
